package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"perm-guard/cache"
	"perm-guard/models"
	"perm-guard/pkg"
	"strconv"
	"time"
)

// 登录
func MoneyLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "登录信息不能为空",
		})
		return
	}

	redis_key := "user_login" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次,禁止登陆",
		})
		return
	}
	var users models.User
	err := models.DB.Where("username=?", username).First(&users).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户或密码错误",
		})
		return
	}
	if users.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if pkg.Md5Str(password) != users.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": "500",
				"msg":  "密码错误三次,封禁两小时",
			})
			return
		} else {
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误",
			})
			return
		}

	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
		"data": users,
	})
	return
}

// 添加
func Add(c *gin.Context) {
	carname := c.PostForm("carname")
	carnum, _ := strconv.Atoi(c.PostForm("carnum"))
	if carname == "" || carnum == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "车辆信息不能为空",
		})
		return
	}
	data := models.Car{
		CarName: carname,
		CarNum:  carnum,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

// 车辆订单添加
func CarOrderAdd(c *gin.Context) {
	cid, _ := strconv.Atoi(c.PostForm("cid"))
	ordername := c.PostForm("ordername")
	orderprice, _ := strconv.Atoi(c.PostForm("orderprice"))
	if cid == 0 || ordername == "" || orderprice == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	data := models.CarOrder{
		Cid:        cid,
		OrderName:  ordername,
		OrderPrice: orderprice,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func CarOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	Offset := (page - 1) * size
	/*
		      SELECT
			  car_orders.id as OrderId,
			  cars.car_name as CarName,
			  cars.car_num AS CarNum,
			  car_orders.order_name AS OrderName,
			  car_orders.order_price AS OrderPrice
			FROM
			  car_orders
			  LEFT JOIN cars ON car_orders.cid = cars.id
	*/
	var list []models.CarOrderList

	redis_key := "car_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("car_orders").
			Select(
				"car_orders.id as OrderId",
				"cars.car_name as CarName",
				"cars.car_num AS CarNum",
				"car_orders.order_name AS OrderName",
				"car_orders.order_price AS OrderPrice",
			).
			Joins("LEFT JOIN cars ON cars.id = car_orders.cid").
			Offset(Offset).
			Limit(size).
			Debug().
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	var total int64
	models.DB.Model(&models.CarOrder{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"list":  list,
		"total": total,
	})
	return
}
func CarOrderDetail(c *gin.Context) {
	id := c.Query("id")
	var list models.CarOrderList

	redis_key := "car_order" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("car_orders").
			Select(
				"car_orders.id as OrderId",
				"cars.car_name as CarName",
				"cars.car_num AS CarNum",
				"car_orders.order_name AS OrderName",
				"car_orders.order_price AS OrderPrice",
			).
			Joins("LEFT JOIN cars ON cars.id = car_orders.cid").
			Where("car_orders.id=?", id).
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": list,
	})
	return
}
